import React,{useState,useRef} from "react";
import styles from './index.module.scss'
import {Card, Breadcrumb, Form, Input,  Button, Space, Radio,message,Upload} from 'antd'
import { Link } from "react-router-dom";
import MyChannels from "@/components/MyChannels";
import ReactQuill from "react-quill";
import 'react-quill/dist/quill.snow.css'
import {PlusOutlined} from '@ant-design/icons'

// 支持的文件类型
const FILETYPE=['image/jpg','image/gif','image/jpeg','image/png']

export default function Publish() {
  const formRef=useRef(null)
  // 图片的数量
  const [type,setType]=useState(1)
  const onTypeChange=(e)=>{
    console.log(e);
    const count=e.target.value
    setType(count)
    // 从 fileRef 中取出图片展示
    setFileList(fileRef.current.slice(0,count))
  }

  const [fileList,setFileList]=useState([])
  // 保存所有的图片
  const fileRef=useRef(fileList)

  function beforeUpload(file) {
    const isImg=FILETYPE.includes(file.type)
    if(!isImg){
      message.error('You can only upload JPG/PNG file!')
    }
    const isLessThan2M=file.size/1024/1024<2
    if(!isLessThan2M) {
      message.error('Image must smaller than 2MB!') 
    }
    return isImg && isLessThan2M
  }
  const onChange=({file,fileList})=>{
    console.log({file,fileList});
    if(FILETYPE.includes(file.type)) {
      setFileList(fileList)
      // 更新fileRef
      fileRef.current=fileList
    }
    formRef.current.validateFields(['type'])
  }
  return (
    <div className={styles.root}>
      <Card title={<Breadcrumb separator='>'>
        <Breadcrumb.Item>
          <Link to='/home'>首页</Link>
        </Breadcrumb.Item>
        <Breadcrumb.Item>发布文章</Breadcrumb.Item>
      </Breadcrumb>}>
          <Form ref={formRef} labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} size="large" initialValues={{content:'',type:1}}>
          <Form.Item label="标题"
           name='title'
           rules={[
               {required:true,message:'标题不能为空'}
           ]}
          >
            <Input
              placeholder="请输入文章标题"
              style={{ width: 400 }}
            ></Input>
          </Form.Item>
          <Form.Item label="频道" 
             name='channel_id'
             rules={[
               {required:true,message:'频道不能为空'}
           ]}
          >
            <MyChannels/>
          </Form.Item>
          <Form.Item label="封面" name='type' 
            rules={[
               {validator(_,value){
                 if(fileList.length!==value){
                   return Promise.reject(new Error(`请上传${value}张图片`))
                 }else{
                   return Promise.resolve()
                 }
               }} 
            ]}
          >
            <Radio.Group value={type} onChange={onTypeChange}>
              <Radio value={1}>单图</Radio>
              <Radio value={3}>三图</Radio>
              <Radio value={0}>无图</Radio>
            </Radio.Group>
					</Form.Item>
        <Form.Item wrapperCol={{offset:4,span:20}}>
          {/* 
          action: 上传的地址
          name: 上传的文件的名字 默认file
          fileList: 显示控制上传的图片, 做回填
          Upload 组件中没有嵌入内容,则整个组件不可见 */}
          <Upload listType="picture-card" fileList={fileList} action='http://toutiao.itheima.net/v1_0/upload' name="image" beforeUpload={beforeUpload} onChange={onChange}
          maxCount={type}
          >  
                 {/* 如果fileList 的长度<type,显示 + */}
                {/* <PlusOutlined /> */}
                {fileList.length<type?<PlusOutlined />:null}
          </Upload>
        </Form.Item>
          <Form.Item label="内容"
           name='content'
            rules={[
               {required:true,message:'内容不能为空'}
           ]}
          >
            <ReactQuill></ReactQuill>
          </Form.Item>

          <Form.Item wrapperCol={{ offset: 4, span: 20 }}>
            <Space>
              <Button type="primary" htmlType="submit">发布文章</Button>
              <Button>存入草稿</Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>
    </div>
  )
}
